<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title></title>
	<script src="./d3.v3.min.js"></script>
</head>
<body>
  <svg id="svg"></svg>
  <svg id="polylinear"></svg>
  <svg id="nest"></svg>
	<script>
		// 浏览器会纠正html不合理的dom结构, 变成如下
		// html
		//   head
		//   body


		// data 绑定数据后, d3提供了inline anonymous function, 内置两个参数, data index
		var data = [15, 50, 22, 8, 100, 10],
		    scaleData = [14, 68, 24500, 430, 19, 1000, 5555] // 但真实的数据, 有可能相差好大

		var yScale = d3.scale.linear().domain([0,24500]).range([0,100]) // 这个时候需要用scale函数, 计算比例尺

		d3.select("#svg")
		  //.attr('width', 300)
			//.attr('height', 150)
			.selectAll("rect")
			//.data(data)
			.data(scaleData)
			.enter()
			.append("rect")
			.attr("width", 10)
			.attr("height", function(d) {return yScale(d);}) 
			.attr("x", function(d,i) {return i * 10;}) // 从左到右
			.attr("y", function(d) {return 100 - yScale(d);}) // 从上到下, 找到data中最高的, 使用差
			.style("fill", "blue")
			.style("stroke", "red")
			.style("stroke-width", "1px")
			.style("opacity", .25);

		//When you deal with such widely diverging values, it often makes more sense to use a polylinear scale. A polylinear scale is a linear scale with multiple points in the domain and range

		var polylinear = d3.scale.linear().domain([0,100,1000,24500]).range([0,50,75,100])

		// 除比例尺不同, 其余同上
		d3.select("#polylinear")
			.selectAll("rect")
			//.data(data)
			.data(scaleData)
			.enter()
			.append("rect")
			.attr("width", 10)
			.attr("height", function(d) {return polylinear(d);}) 
			.attr("x", function(d,i) {return i * 10;}) // 从左到右
			.attr("y", function(d) {return 100 - polylinear(d);}) // 从上到下, 找到data中最高的, 使用差
			.style("fill", "blue")
			.style("stroke", "red")
			.style("stroke-width", "1px")
			.style("opacity", .25);

 
		// clamp(), 超出极限值时, 返回极限值
    var yScale = d3.scale.linear()
               .domain([0,100,500])
               .range([0,50,100])
               .clamp(true);
    
		// nest 
		d3.json("tweets.json",function(error,data) {dataViz(data.tweets)})

		function dataViz(incomingData) {
		  var nestedTweets = d3.nest()
			   .key(function (el) {return el.user;})
			   .entries(incomingData);
		  
			nestedTweets.forEach(function (el) {
				el.numTweets = el.values.length;
			})

			var maxTweets = d3.max(nestedTweets, function(el) {return el.numTweets;});

			var yScale = d3.scale.linear().domain([0,maxTweets]).range([0,100]);

			d3.select("#nest")
			  .selectAll("rect")
				.data(nestedTweets)
				.enter()
				.append("rect")
				.attr("width", 50)
				.attr("height", function(d) {return yScale(d.numTweets);})
				.attr("x", function(d,i) {return i * 60;})
				.attr("y", function(d) {return 100 - yScale(d.numTweets);})
				.style("fill", "blue")
				.style("stroke", "red")
				.style("stroke-width", "1px").style("opacity", .25);



		}

</script>
</body>
</html>
